package com.ruoyi.bluebera.task;


import com.ruoyi.bluebera.domain.*;
import com.ruoyi.bluebera.service.*;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.net.Proxy;
import java.net.InetSocketAddress;


import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component("allOrderProcessor")

public class AllOrderProcessor {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS) // 连接超时
            .readTimeout(15, TimeUnit.SECONDS)    // 读超时
            .writeTimeout(10, TimeUnit.SECONDS)   // 写超时
            //.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 10080))) // 本地 HTTP 代理
            .build();

    @Autowired
    private IBizOrdersService bizOrdersService;
    @Autowired
    private IBizTxScanLogsService bizTxScanLogsService;
    @Autowired
    private IBizTxRecordService bizTxRecordService;
    @Autowired
    private IBizExchangeRatesService bizExchangeRatesService;


    @Transactional
    public void processOrder() {
        // 1. get all preprocessing
        BizOrders bizOrders = new BizOrders();
        bizOrders.setTxStatus(TaskConstants.STATUS_PROCESSING);
        //bizOrders.setNetwork(TaskConstants.BERA_CHAINId);
        List<BizOrders> list = bizOrdersService.selectBizOrdersList(bizOrders);
        logger.info("processOrder list={}", list);
        // 2. process according token
        for (BizOrders order : list) {

            BizTxRecord txRecord = new BizTxRecord();
            txRecord.setHash(order.getTxHash());
            //txRecord.setChainId(TaskConstants.BERA_CHAINId);
            // change order status and txstatus
            List<BizTxRecord> txRecordList = bizTxRecordService.selectBizTxRecordList(txRecord);
            logger.info("processOrder txRecordList={}",txRecordList);
            for(BizTxRecord item : txRecordList) {
                logger.info("processOrder item={}",item);
                if (item.getConfirmations()>TaskConstants.CONFIRM_COUNT) {
                    // add content to tx log
                    BizTxScanLogs bizTxScanLogs = new BizTxScanLogs();
                /*
                amount DECIMAL(36, 18) default NULL COMMENT '数量',
                bluebera_amount DECIMAL(36, 18) default NULL COMMENT '兑换的bluebera数量',
                rate_to_bluebera DECIMAL(18, 8) default NULL COMMENT '兑换bluebera汇率',
                 */
                    //  need tx info
                    bizTxScanLogs.setOrderId(order.getId());
                    bizTxScanLogs.setPaymentAddress(item.getFromAddr());  // from block
                    bizTxScanLogs.setTxHash(order.getTxHash());
                    bizTxScanLogs.setTokenSymbol(order.getTokenSymbol());
                    bizTxScanLogs.setNetwork(order.getNetwork());

                    bizTxScanLogs.setAmount(item.getValue()); // from block
                    // bera chain native
                    if (TaskConstants.BERA_CHAINId.equals(item.getChainId()) &&
                            (item.getContractAddress() == null || item.getContractAddress().trim().isEmpty())) {
                        BizExchangeRates rateToBluebera = bizExchangeRatesService.selectClosestExchangeRate(item.getBlockTime()); // block time
                        bizTxScanLogs.setRateToBluebera(rateToBluebera.getRateToBluebera());
                        bizTxScanLogs.setBlueberaAmount(item.getValue().divide(rateToBluebera.getRateToBluebera())); // from block value/rate
                    } else {
                        bizTxScanLogs.setBlueberaAmount(item.getValue().divide(new BigDecimal("0.02")));
                        bizTxScanLogs.setRateToBluebera(new BigDecimal("0.02"));
                    }

                    bizTxScanLogs.setScannedAt(new Date());
                    bizTxScanLogs.setScanStatus(TaskConstants.STATUS_COMPLETED);
                    bizTxScanLogsService.insertBizTxScanLogs(bizTxScanLogs);

                    // update order
                    order.setTxStatus(TaskConstants.STATUS_COMPLETED);
                    order.setStatus(TaskConstants.STATUS_COMPLETED);
                    bizOrdersService.updateBizOrders(order);
                    logger.warn("updated order={}", order);
                }
            }
        }

    }

}


